package com.itic.system.order.order.service;

import com.itic.appbase.applications.redis.IRedisDao;
import com.itic.appbase.framework.Base.BaseCode;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.config.HPPConfig;
import com.itic.appbase.framework.type.*;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.ExpressUtil;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.RandomOrderNumHelper;
import com.itic.appbase.framework.utils.WXPay.WXPayResult;
import com.itic.appbase.framework.utils.WXPay.WXRefundResult;
import com.itic.appbase.framework.utils.WXPay.WeixinUtil;
import com.itic.system.collage.collage.persistence.model.Collage;
import com.itic.system.collage.collage.service.CollageService;
import com.itic.system.collage.condition.persistence.model.CollageCondition;
import com.itic.system.collage.condition.service.CollageConditionService;
import com.itic.system.collage.imageVideo.persistence.model.CollageImageVideo;
import com.itic.system.collage.imageVideo.service.CollageImageVideoService;
import com.itic.system.collage.skuProperty.persistence.model.CollageSkuProperty;
import com.itic.system.collage.skuProperty.service.CollageSkuPropertyService;
import com.itic.system.order.orderAfterSale.persistence.model.OrderAfterSale;
import com.itic.system.order.orderAfterSale.service.OrderAfterSaleService;
import com.itic.system.pay.userPay.persistence.model.PayUserLog;
import com.itic.system.pay.userPay.service.PayUserLogService;
import com.itic.system.project.express.persistence.model.ProjectExpress;
import com.itic.system.project.express.service.ProjectExpressService;
import com.itic.system.self.selfLifting.persistence.model.SelfLifting;
import com.itic.system.self.selfLifting.service.SelfLiftingService;
import com.itic.system.user.address.persistence.model.UserAddress;
import com.itic.system.user.address.service.UserAddressService;
import com.itic.system.user.attention.persistence.model.UserAttention;
import com.itic.system.user.attention.service.UserAttentionService;
import com.itic.system.user.user.persistence.model.HppUser;
import com.itic.system.user.user.service.HppUserService;
import com.itic.system.vo.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.system.order.order.persistence.dao.OrderDao;
import com.itic.system.order.order.persistence.model.Order;
import com.itic.system.order.order.persistence.model.OrderExample;
import com.itic.system.order.order.persistence.model.OrderExample.Criteria;

import java.text.ParseException;
import java.util.*;


@Service
@Transactional
public class OrderService
     extends CrudService<OrderDao,Order,OrderExample> {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private CollageService collageService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private CollageSkuPropertyService collageSkuPropertyService;
    @Autowired
    private SelfLiftingService selfLiftingService;
    @Autowired
    private HppUserService hppUserService;
    @Autowired
    private CollageConditionService collageConditionService;
    @Autowired
    private CollageImageVideoService collageImageVideoService;
    @Autowired
    private ProjectExpressService projectExpressService;
    @Autowired
    private OrderAfterSaleService orderAfterSaleService;
    @Autowired
    private PayUserLogService payUserLogService;
    @Autowired
    private IRedisDao<String,Object> redisDao;
    @Autowired
    private UserAttentionService userAttentionService;

    public  Map<String,Object> submitOrder(SubmitOrderVo submitOrderVo) throws InterruptedException {
        Map<String,Object> resultMap = new HashMap<>();
        //获取拼团信息
        StringBuffer keyLock = new StringBuffer(RedisKey.SubmitOrderLock.getKey()).append(submitOrderVo.getCollageId());
        Object vaule = this.redisDao.get(keyLock.toString());
        int i = 0;
        while (vaule!=null){
            Thread.sleep(5000);
            vaule = this.redisDao.get(keyLock.toString());
            if(vaule==null)
                break;
            i++;
            if(i>3)
                break;
        }
        this.redisDao.set(keyLock.toString(),keyLock.toString(),60);
        Collage collage = this.collageService.get(submitOrderVo.getCollageId());
        if(collage!=null){
            //效验拼团信息是否合理 返回错误信息
            boolean flag = this.checkSubmitOrderVo(submitOrderVo,resultMap,collage);
            if(flag){
                //下拼团订单
                Order order = null;
                //拼团类型
                Double collagePrice = null;
                CollageType collageType = CollageType.getCollageType(collage.getCollageType());
                switch (collageType){
                    case Ladder:
                        break;
                    case Common:
                        //查看普通拼团的拼团价格
                        List<CollageCondition> collageConditions =  this.collageConditionService.findCollageConditionByCollageId(collage.getId());
                        if(!collageConditions.isEmpty()){
                            CollageCondition collageCondition = collageConditions.get(0);
                            collagePrice = collageCondition.getCollagePrice();
                        }
                        break;
                }
                //支付方式 担保 直接
                String isBelive=null;
                PayMethod payMethod = PayMethod.getPayMethod(collage.getPayMethod());
                switch (payMethod){
                    case GuaranteePay:
                        break;
                    case DirectToAccount:
                        isBelive = "1";
                        break;
                }
                String orderNo = RandomOrderNumHelper.getOrderNumber();
                String skuName = null;
                String skuPropertyId = null;
                if(StringUtils.isNotEmpty(submitOrderVo.getSkuIds())){
                    CollageSkuProperty collageSkuProperty =  this.collageSkuPropertyService.getCollageSkuPropertyByCollageIdAndProperty(collage.getId(),submitOrderVo.getSkuIds());
                    //规格匹配名称
                    skuName = collageSkuProperty.getPropertyName();
                    skuPropertyId = collageSkuProperty.getId();
                }
                //拼团类型 发货方式
                DeliveryMethod deliveryMethod = DeliveryMethod.getDeliveryMethod(collage.getDeliverMethod());
                switch (deliveryMethod){
                    //配送发货
                    case Delivery:
                        UserAddress userAddress = this.userAddressService.get(submitOrderVo.getAddressId());
                        order = this.addDeliveryOrder(collageType,collage.getId(),submitOrderVo.getUserId(),collage.getUserId(),collage.getTitle(),orderNo,collage.getOriginalPrice(),collagePrice,submitOrderVo.getName(),submitOrderVo.getPhone(),submitOrderVo.getActualPay(),submitOrderVo.getFee(),deliveryMethod,payMethod,submitOrderVo.getLeaveMsg(),skuName,userAddress,isBelive,OrderState.Paying,skuPropertyId,submitOrderVo.getCount());
                        break;
                    //自提点
                    case Self:
                        SelfLifting selfLifting = this.selfLiftingService.get(submitOrderVo.getSelfAddressId());
                        order = this.addSelfOrder(collageType,collage.getId(),submitOrderVo.getUserId(),collage.getUserId(),collage.getTitle(),orderNo,collage.getOriginalPrice(),collagePrice,submitOrderVo.getName(),submitOrderVo.getPhone(),submitOrderVo.getActualPay(),submitOrderVo.getFee(),deliveryMethod,payMethod,submitOrderVo.getLeaveMsg(),skuName,selfLifting,isBelive,OrderState.Paying,skuPropertyId,submitOrderVo.getCount());
                        break;
                    //二维码
                    case QCode:
                        //TODO 二维码待定...
                        break;
                    //虚拟吗
                    case VirtualCode:
                        //TODO 虚拟吗待定...
                        break;
                }
                if(order!=null){
                    //调起微信支付
                    HppUser user = this.hppUserService.get(submitOrderVo.getUserId());
                    String openId=user.getOpenId();
                    String appId = "wx0d2c39ed5fab1f51";
                    String mchId="1501717851";
                    String appSecret = "9ebcda3b0d16443c9c9734ea3e1e02f5";
                    double actualPay = order.getActualPay() + (order.getFee()==null?0:order.getFee());
                    WXPayResult wxPayResult =  WeixinUtil.wxPay(openId,appId,mchId,appSecret,orderNo,actualPay,"47.92.134.181","123123123");
                    //验证微信调起是成功
                    if("SUCCESS".equals(wxPayResult.getError_code())) {
                        JSONObject obj = wxPayResult.getResult();
                        obj.put("orderNo", orderNo);
                        resultMap.put(BaseCode.DATA, obj);
                        resultMap.put(BaseCode.CODE, BaseCode.SUCCESS_ERROR_CODE);
                        resultMap.put(BaseCode.MSG, BaseCode.SUCCESS_ERROR_MSG);
                        //将次购买者添加的到参团队列 并设置1分钟内不支付自动提出队列
                        StringBuffer key = new StringBuffer(RedisKey.CollageBuyUser.getKey()).append(submitOrderVo.getCollageId()).append(submitOrderVo.getUserId());
                        this.redisDao.set(key.toString(),key.toString(),60);
                        //将参团人 添加为发布拼团人的粉丝
                        List<UserAttention> userAttentions = this.userAttentionService.findUserAttentionByAttentionUserIdAndUserId(order.getSellerUserId(),order.getBuyUserId());
                        if(userAttentions.isEmpty())
                            this.userAttentionService.addUserAttention(order.getSellerUserId(),order.getBuyUserId());
                    }else {
                        //若不成功 返回微信调起失败
                        resultMap.put(BaseCode.CODE, BaseCode.HPP_WX_PAY_NOT_SUCCESS_CODE);
                        resultMap.put(BaseCode.MSG, BaseCode.HPP_WX_PAY_NOT_SUCCESS_MSG);
                    }
                }else{
                    //订单支付失败
                    resultMap.put(BaseCode.CODE, BaseCode.HPP_ORDER_PAY_ERROR_CODE);
                    resultMap.put(BaseCode.MSG, BaseCode.HPP_ORDER_PAY_ERROR_MSG);
                }
            }
        }else{
            //提示拼团不存在
            resultMap.put(BaseCode.CODE, BaseCode.HPP_COLLAGE_NOT_EXIST_CODE);
            resultMap.put(BaseCode.MSG, BaseCode.HPP_COLLAGE_NOT_EXIST_MSG);
        }
        return resultMap;
    }

    /**
     * 效验拼团参数是否合理 返回错误信息
     * @param submitOrderVo 拼团信息
     * @param resultMap 错误参数 返回结果
     * @param collage 拼团
     * @return
     */
    public  boolean checkSubmitOrderVo(SubmitOrderVo submitOrderVo,Map<String,Object> resultMap,Collage collage){
        boolean flag = true;
        if(ckeckSubmitOrderParams(submitOrderVo)){
            //效验并发问题 使用redis锁 最大拼团人数
            Integer peopleMaxCount = (Integer) this.redisDao.get(RedisKey.CollageMaxPeopleCount+submitOrderVo.getCollageId());
            if(peopleMaxCount !=null){
                StringBuffer keysCollageBuyUser = new StringBuffer(RedisKey.CollageBuyUser.getKey()).append(submitOrderVo.getCollageId()).append("*");
                Set<String> keys = this.redisDao.keys(keysCollageBuyUser.toString());
                //效验拼团队列人数是否小于拼团最大人数
                if(keys.size() < peopleMaxCount){
                    //购买人 拼团id 商品规格 拼团价 收货地址 运费模板是否限购 运费 支付金额 收货地址Id
                    //效验参数 (担保支付 直接支付) 团是否结束 成团人数 配送类型(配送，自提，虚拟吗 二维码)
                    CollageEndState collageEndState =collageService.IsCollageEnd(collage);
                    //效验拼团是否结束
                    if(CollageEndState.NotEnd.getState().equals(collageEndState.getState())){
                        //效验商品库存是否足够
                        if(StringUtils.isNotEmpty(submitOrderVo.getSkuIds())){
                            CollageSkuProperty collageSkuProperty =  this.collageSkuPropertyService.getCollageSkuPropertyByCollageIdAndProperty(collage.getId(),submitOrderVo.getSkuIds());
                            if(collageSkuProperty ==null || submitOrderVo.getCount()>collageSkuProperty.getInventorys()){
                                flag = false;
                                //提示用户库存不足
                                resultMap.put(BaseCode.CODE, BaseCode.HPP_COLLAGE_SKU_PROPERTY_INVENTORYS_NOT_ENOUGH_CODE);
                                resultMap.put(BaseCode.MSG, BaseCode.HPP_COLLAGE_SKU_PROPERTY_INVENTORYS_NOT_ENOUGH_MSG);
                            }
                        }
                        //配送类型
                        DeliveryMethod deliveryMethod = DeliveryMethod.getDeliveryMethod(collage.getDeliverMethod());
                        switch (deliveryMethod){
                            //配送发货
                            case Delivery:
                                //TODO 判断该地区是否限购 (后期完善)
                                //效验收货地址
                                UserAddress userAddress = null;
                                if(StringUtils.isEmpty(submitOrderVo.getAddressId()) ||  (userAddress =this.userAddressService.get(submitOrderVo.getAddressId()) )==null){
                                    //提示收货地址不存在
                                    resultMap.put(BaseCode.CODE,BaseCode.HPP_USER_ADDRESS_NOT_EXIST_CODE);
                                    resultMap.put(BaseCode.MSG,BaseCode.HPP_USER_ADDRESS_NOT_EXIST_MSG);
                                    flag = false;
                                }
                                break;
                            //自提点
                            case Self:
                                //效验自提点参数
                                SelfLifting selfLifting = null;
                                if(StringUtils.isEmpty(submitOrderVo.getSelfAddressId()) || (selfLifting = this.selfLiftingService.get(submitOrderVo.getSelfAddressId()))==null){
                                    //提示自提点不存在
                                    resultMap.put(BaseCode.CODE,BaseCode.HPP_SELF_NOT_EXIST_CODE);
                                    resultMap.put(BaseCode.MSG,BaseCode.HPP_SELF_NOT_EXIST_MSG);
                                    flag = false;
                                }
                                break;
                            //二维码
                            case QCode:
                                break;
                            //虚拟吗
                            case VirtualCode:
                                break;
                        }
                    }else{
                        //提示拼团已结束
                        resultMap.put(BaseCode.CODE, BaseCode.HPP_COLLAGE_ALREADY_END_CODE);
                        resultMap.put(BaseCode.MSG, BaseCode.HPP_COLLAGE_ALREADY_END_MSG);
                        flag = false;
                    }
                }else{
                    flag = false;
                    //提示拼团队列已满,请稍后购买
                    resultMap.put(BaseCode.CODE, BaseCode.HPP_COLLAGE_QUEUE_ALREADY_ENOUGH_CODE);
                    resultMap.put(BaseCode.MSG, BaseCode.HPP_COLLAGE_QUEUE_ALREADY_ENOUGH_MSG);
                }
            }else{
                flag = false;
                //提示拼团已结束
                resultMap.put(BaseCode.CODE, BaseCode.HPP_COLLAGE_ALREADY_END_CODE);
                resultMap.put(BaseCode.MSG, BaseCode.HPP_COLLAGE_ALREADY_END_MSG);
            }
        }else{
            flag = false;
            resultMap.put(BaseCode.CODE, BaseCode.PARAM_ERROR_CODE);
            resultMap.put(BaseCode.MSG, BaseCode.PARAM_ERROR_MSG);
        }
        return flag;
    }

    /**
     *  效验拼团参数是否合理
     * @param submitOrderVo 拼团信息
     * @return
     */
    public  boolean ckeckSubmitOrderParams(SubmitOrderVo submitOrderVo){
        boolean flag = true;
        if(submitOrderVo!=null && submitOrderVo.getActualPay()!=null && submitOrderVo.getCount()!=null && StringUtils.isNoneBlank(submitOrderVo.getCollageId(),submitOrderVo.getUserId()))
            flag = true;
        else
            flag =false;
        return flag ;
    }

    /**
     * 初始化订单类
     * @param collageId
     * @param buyUserId
     * @param sellerUserId
     * @param title
     * @param orderNo
     * @param originalPrice
     * @param collagePrice
     * @param reciveName
     * @param recivePhone
     * @param actualPay
     * @param fee
     * @param deliveryMethod
     * @param payMethod
     * @param leaveMsg
     * @return
     */
    public Order generalOrder(CollageType collageType, String collageId, String buyUserId, String sellerUserId, String title, String orderNo, double originalPrice, Double collagePrice, String reciveName, String recivePhone, double actualPay, double fee, DeliveryMethod deliveryMethod, PayMethod payMethod, String leaveMsg, String skuName, String isBelive, OrderState orderState,String skuPropertyId){
        Order order = new Order();
        order.setSellerUserId(sellerUserId);
        order.setCollageId(collageId);
        order.setBuyUserId(buyUserId);
        order.setCollagePrice(collagePrice);
        order.setDeliverMethod(deliveryMethod.getMethod());
        order.setLeavingMessage(leaveMsg);
        order.setOrderNo(orderNo);
        order.setOriginalPrice(originalPrice);
        order.setReciveName(reciveName);
        order.setRecivePhone(recivePhone);
        order.setTitle(title);
        order.setFee(fee);
        //支付行为 担保 直接
        order.setPayMethod(payMethod.getMethod());
        order.setActualPay(actualPay);
        order.setSkuName(skuName);
        order.setSkuPropertyId(skuPropertyId);
        //拼团类型
        order.setCollageType(collageType.getType());
        //是否信任该团长
        order.setIsBelive(isBelive);
        order.setState(orderState.getState());
        order.setIsTradeCollage(TradeCollageType.No.getType());
        return order;
    }

    /**
     * 重载generalOrder方法 添加 地址参数
     * @param collageType
     * @param collageId
     * @param buyUserId
     * @param sellerUserId
     * @param title
     * @param orderNo
     * @param originalPrice
     * @param collagePrice
     * @param reciveName
     * @param recivePhone
     * @param actualPay
     * @param fee
     * @param deliveryMethod
     * @param payMethod
     * @param leaveMsg
     * @param skuName
     * @param isBelive
     * @param address
     * @param province
     * @param provinceId
     * @param city
     * @param cityId
     * @param region
     * @param regionId
     * @return
     */
    public Order generalOrder(CollageType collageType,String collageId,String buyUserId,String sellerUserId,String title,String orderNo,double originalPrice,Double collagePrice,String reciveName,String recivePhone,double actualPay,double fee,DeliveryMethod deliveryMethod,PayMethod payMethod,String leaveMsg,String skuName,String isBelive,String address,String province,String provinceId,String city,String cityId,String region,String regionId,OrderState orderState,String skuPropertyId,int count){
        Order order = this.generalOrder(collageType,collageId,buyUserId,sellerUserId,title,orderNo,originalPrice,collagePrice,reciveName,recivePhone,actualPay,fee,deliveryMethod,payMethod,leaveMsg,skuName,isBelive,orderState,skuPropertyId);
        order.setAddress(address);
        order.setProvince(province);
        order.setProvinceId(provinceId);
        order.setCity(city);
        order.setCityId(cityId);
        order.setRegion(region);
        order.setRegionId(regionId);
        order.setCount(count);
        return order;
    }



    /**
     * 添加配送订单
     * @param collageType
     * @param collageId
     * @param buyUserId
     * @param sellerUserId
     * @param title
     * @param orderNo
     * @param originalPrice
     * @param collagePrice
     * @param reciveName
     * @param recivePhone
     * @param actualPay
     * @param fee
     * @param deliveryMethod
     * @param payMethod
     * @param leaveMsg
     * @param skuName
     * @param userAddress
     * @param isBelive
     * @return
     */
    public Order  addDeliveryOrder(CollageType collageType,String collageId,String buyUserId,String sellerUserId,String title,String orderNo,double originalPrice,double collagePrice,String reciveName,String recivePhone,double actualPay,double fee,DeliveryMethod deliveryMethod,PayMethod payMethod,String leaveMsg,String skuName,UserAddress userAddress,String isBelive,OrderState orderState,String skuPropertyId,int count){
        Order order =  this.generalOrder(collageType,collageId,buyUserId,sellerUserId,title,orderNo,originalPrice,collagePrice,reciveName,recivePhone,actualPay,fee,deliveryMethod,payMethod,leaveMsg,skuName,isBelive,userAddress.getAddress(),userAddress.getProvinceName(),userAddress.getProvinceId(),userAddress.getCityName(),userAddress.getCityId(),userAddress.getRegionName(),userAddress.getRegionId(),orderState,skuPropertyId,count);
        String result = this.add(order);
        if(SUCCESS.equals(result))
            return order;
        else
            return null;
    }

    /**
     * 添加自提订单
     * @param collageType
     * @param collageId
     * @param buyUserId
     * @param sellerUserId
     * @param title
     * @param orderNo
     * @param originalPrice
     * @param collagePrice
     * @param reciveName
     * @param recivePhone
     * @param actualPay
     * @param fee
     * @param deliveryMethod
     * @param payMethod
     * @param leaveMsg
     * @param skuName
     * @param selfLifting
     * @param isBelive
     * @return
     */
    public Order  addSelfOrder(CollageType collageType,String collageId,String buyUserId,String sellerUserId,String title,String orderNo,double originalPrice,double collagePrice,String reciveName,String recivePhone,double actualPay,double fee,DeliveryMethod deliveryMethod,PayMethod payMethod,String leaveMsg,String skuName,SelfLifting selfLifting,String isBelive,OrderState orderState,String skuPropertyId,int count){
        Order order =  this.generalOrder(collageType,collageId,buyUserId,sellerUserId,title,orderNo,originalPrice,collagePrice,reciveName,recivePhone,actualPay,fee,deliveryMethod,payMethod,leaveMsg,skuName,isBelive,selfLifting.getAddress(),selfLifting.getProvinceName(),selfLifting.getProvinceId(),selfLifting.getCityName(),selfLifting.getCityId(),selfLifting.getRegionName(),selfLifting.getRegionId(),orderState,skuPropertyId,count);
        String result = this.add(order);
        if(SUCCESS.equals(result))
            return order;
        else
            return null;
    }

    /**
     * 我是团员是 我的订单列表
     * @param orderState
     * @param userId
     * @param example
     * @return
     */
    public List<OrderListVo> myOrderList(OrderState orderState ,String userId,OrderExample example){
        //分页查询我的订单(我是团员时候)
        List<Order> orders = this.findMyOrderListByStateAndUserIdAndPage(orderState,userId,example);
        List<OrderListVo> orderListVos = new ArrayList<>();
        for(Order order : orders){
            OrderListVo orderListVo = this.orderWrapToOrderListVo(order);
            orderListVos.add(orderListVo);
        }
        return orderListVos;
    }

    /**
     * 将order转换成 OrderListVo
     * @param order
     * @return
     */
    public OrderListVo orderWrapToOrderListVo(Order order){
        OrderListVo orderListVo = new OrderListVo();
        //订单号
        orderListVo.setOrderNo(order.getOrderNo());
        //运费
        double fee = order.getFee() ==null ?0 : order.getFee();
        orderListVo.setFee(fee);
        //订单状态
        OrderState orderState = OrderState.getOrderState(order.getState());
        orderListVo.setState(orderState.getState());
        orderListVo.setOrderStateContent(orderState.getName());
        //商品总数量
        orderListVo.setTotalCount(order.getCount());
        //实付款
        double actualPay =order.getActualPay() + fee;
        orderListVo.setActualPay(actualPay);
        Collage collage = this.collageService.get(order.getCollageId());
        OrderSkuVo orderSkuVo = this.getOrderSkuVo(collage,order);
        orderListVo.setOrderSkuVo(orderSkuVo);
        //订单售后处理状态
        OrderAfterSale orderAfterSale = this.orderAfterSaleService.getOrderAfterSaleByOrderNo(order.getOrderNo());
        if(orderAfterSale!=null)
            orderListVo.setDealState(orderAfterSale.getDealState());
        String sendMehod = order.getSendMethod();
        orderListVo.setSendMethod(sendMehod);
        return orderListVo;
    }

    /**
     * 将collage order 转换成 OrderSkuVo
     * @param collage
     * @param order
     * @return
     */
    public  OrderSkuVo getOrderSkuVo(Collage collage , Order order){
        OrderSkuVo orderSkuVo = new OrderSkuVo();
        //商品拼团价格
        List<CollageCondition> collageConditions = this.collageConditionService.findCollageConditionByCollageId(collage.getId());
        //商品标题
        orderSkuVo.setTitle(collage.getTitle());
        if(!collageConditions.isEmpty())
            orderSkuVo.setCollagePrice(collageConditions.get(0).getCollagePrice());
        orderSkuVo.setCount(order.getCount());
        //商品图片
        List<CollageImageVideo> collageImageVideos = this.collageImageVideoService.findCollageImageVideoByCollageId(collage.getId());
        if(!collageImageVideos.isEmpty())
            orderSkuVo.setGoodImage(collageImageVideos.get(0).getUrl());
        //规格
        if(StringUtils.isNotEmpty(order.getSkuPropertyId())){
            CollageSkuProperty collageSkuProperty = this.collageSkuPropertyService.get(order.getSkuPropertyId());
            List<OrderSkuPropertyVo> orderSkuPropertyVos = this.collageSkuPropertyService.collageSkuPropertyWrapToOrderSkuPropertyVo(collageSkuProperty);
            orderSkuVo.setOrderSkuPropertyVos(orderSkuPropertyVos);
        }
        return orderSkuVo;
    }

    /**
     * 根据订单状态 分页查询我的订单列表
     * @param orderState 订单状态
     * @param userId 用户Id
     * @param example 分页example
     * @return
     */
    public List<Order> findMyOrderListByStateAndUserIdAndPage(OrderState orderState ,String userId,OrderExample example){
        Criteria criteria = example.createCriteria();
        criteria.andStateEqualTo(orderState.getState());
        criteria.andBuyUserIdEqualTo(userId);
        criteria.andIsEffectiveEqualTo(DBConst.TRUE);
        List<Order> orders = this.list(example);
        return orders;
    }

    /**
     * 根据订单状态 分页查询我发布的拼团的订单列表
     * @param orderState
     * @param userId
     * @param example
     * @return
     */
    public List<Order> findMyCollageOrderListByStateAndUserIdAndPage(OrderState orderState ,String userId,OrderExample example){
        Criteria criteria = example.createCriteria();
        criteria.andStateEqualTo(orderState.getState());
        criteria.andSellerUserIdEqualTo(userId);
        criteria.andIsEffectiveEqualTo(DBConst.TRUE);
        List<Order> orders = this.list(example);
        return orders;
    }

    /**
     * 我发布的团的订单列表
     * @param orderState
     * @param userId
     * @param example
     * @return
     */
    public List<OrderListVo> myCollageOrderList(OrderState orderState ,String userId,OrderExample example){
        Map<String,Object> resultMap = new HashMap<>();
        //分页查询我的订单(我是团员时候)
        List<Order> orders = this.findMyCollageOrderListByStateAndUserIdAndPage(orderState,userId,example);
        List<OrderListVo> orderListVos = new ArrayList<>();
        for(Order order : orders){
            OrderListVo orderListVo = this.orderWrapToOrderListVo(order);
            orderListVos.add(orderListVo);
        }
        return orderListVos;
    }

    /**
     * 根据订单号查询订单
     * @param orderNo
     * @return
     */
    public Order getOrderByOrderNo(String orderNo){
        Order order = this.orderDao.getOrderByOrderNo(orderNo);
        return order;
    }

    public OrderDetailVo orderDetail(String orderNo){
        Order order = this.getOrderByOrderNo(orderNo);
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        //订单状态
        orderDetailVo.setOrderState(order.getState());
        //订单号
        orderDetailVo.setOrderNo(order.getOrderNo());
        //运费
        double fee = order.getFee() ==null ?0: order.getFee();
        orderDetailVo.setFee(fee);
        //实付款
        double actualPay = order.getActualPay() + fee;
        orderDetailVo.setActualPay(actualPay);
        //订单创建时间
        orderDetailVo.setCreateTime(order.getCreateTime());
        //收货地址
        String address = order.getProvince() + order.getCity()+order.getRegion() + order.getAddress();
        orderDetailVo.setAddress(address);
        //收货人名称
        orderDetailVo.setReciveName(order.getReciveName());
        //收货人手机号
        orderDetailVo.setRevicePhone(order.getRecivePhone());
        //订单总数量
        orderDetailVo.setTotalCount(order.getCount());
        //商品总额
        orderDetailVo.setTotalPrice(order.getActualPay());
        DeliveryMethod deliveryMethod = DeliveryMethod.getDeliveryMethod(order.getDeliverMethod());
        orderDetailVo.setOrderType(deliveryMethod.getMethod());
        switch (deliveryMethod){
            case Delivery:
                break;
            case Self:
                break;
            case QCode:
                break;
            case VirtualCode:
                break;
        }
        //拼团
        Collage collage = this.collageService.get(order.getCollageId());
        //拼团里商品sku
        OrderSkuVo orderSkuVo = this.getOrderSkuVo(collage,order);
        List<OrderSkuVo> orderSkuVos = new ArrayList<>();
        orderSkuVos.add(orderSkuVo);
        orderDetailVo.setOrderSkuVos(orderSkuVos);
        HppUser hppUser  = this.hppUserService.get(order.getSellerUserId());
        if(hppUser!=null){
            CollageHeadInfoVo collageHeadInfoVo = this.hppUserService.getCollageHeadInfoVo(hppUser);
            orderDetailVo.setCollageHeadInfoVo(collageHeadInfoVo);
        }
        PayUserLog payUserLog = this.payUserLogService.getPayUserLogByOrderNo(orderNo);
        //支付时间
        if(payUserLog!=null)
            orderDetailVo.setPayTime(payUserLog.getCreateTime());
        //TODO 收货时间
         //orderDetailVo.setConfirmReciveDate(order.get);
        //退款状态
        OrderAfterSale orderAfterSale = this.orderAfterSaleService.getOrderAfterSaleByOrderNo(orderNo);
        if(orderAfterSale!=null){
            DealState dealState = DealState.getDealState(orderAfterSale.getDealState());
            orderDetailVo.setDealState(dealState.getState());
            orderDetailVo.setDealStateContent(dealState.getName());
            //失败原因
            orderDetailVo.setReason(orderAfterSale.getRefundFailReason());
        }
        //团长的userId
        orderDetailVo.setCollageUserId(collage.getUserId());
        orderDetailVo.setSendMethod(order.getSendMethod());
        return orderDetailVo;
    }

    /**
     * 查看某个团参团人数(代发货状态)不成团不可发货
     * @param collageId
     * @return
     */
    public int findOrderCountByCollageId(String collageId){
        OrderExample example = new OrderExample();
        Criteria criteria = example.createCriteria();
        criteria.andCollageIdEqualTo(collageId);
        criteria.andStateNotEqualTo(OrderState.Paying.getState());
        int  joinCount = this.count(example);
        return joinCount;
    }

    /**
     * 通过条件分页查询后台管理订单
     * @param orderConditionVo
     * @param example
     * @throws ParseException
     */
    public List<Order> findManageOrderListByOrderConditionVo(OrderConditionVo orderConditionVo, OrderExample example) throws ParseException {
        Criteria criteria = example.createCriteria();
        if(StringUtils.isNotEmpty(orderConditionVo.getState()))
            criteria.andStateEqualTo(orderConditionVo.getState());
        if(StringUtils.isNotEmpty(orderConditionVo.getUserId()))
            criteria.andSellerUserIdEqualTo(orderConditionVo.getUserId());
        if(StringUtils.isNotEmpty(orderConditionVo.getOrderNo()))
            criteria.andOrderNoEqualTo(orderConditionVo.getOrderNo());
        if(StringUtils.isNotEmpty(orderConditionVo.getReviceName()))
            criteria.andReciveNameEqualTo(orderConditionVo.getReviceName());
        if(StringUtils.isNotEmpty(orderConditionVo.getRevicePhone()))
            criteria.andRecivePhoneEqualTo(orderConditionVo.getRevicePhone());
        if(StringUtils.isNotEmpty(orderConditionVo.getOrderType()))
            criteria.andOrderTypeEqualTo(orderConditionVo.getOrderType());
        if(StringUtils.isNotEmpty(orderConditionVo.getCarrageNo()))
            criteria.andExpressNoEqualTo(orderConditionVo.getCarrageNo());
        if(StringUtils.isNotEmpty(orderConditionVo.getStartTime()))
            criteria.andCreateTimeGreaterThanOrEqualTo(DateHelper.parseDate(orderConditionVo.getStartTime(),"yyyy-MM-dd"));
        if(StringUtils.isNotEmpty(orderConditionVo.getEndTime()))
            criteria.andCreateTimeLessThanOrEqualTo(DateHelper.parseDate(orderConditionVo.getEndTime(),"yyyy-MM-dd"));
        criteria.andIsEffectiveEqualTo(DBConst.TRUE);
        List<Order> orders = this.list(example);
        return orders;
    }

    /**
     * 后台管理订单搜索列表
     * @param orderConditionVo
     * @param example
     * @return
     * @throws ParseException
     */
    public Map<String,Object> manageOrderList(OrderConditionVo orderConditionVo,OrderExample example) throws ParseException {
        Map<String,Object> resultMap = new HashMap<>();
        HppUser hppUser = this.hppUserService.get(orderConditionVo.getUserId());
        if(hppUser!= null){
            List<Order> orders = this.findManageOrderListByOrderConditionVo(orderConditionVo,example);
            List<OrderMamgerListVo> orderMamgerListVos = new ArrayList<>();
            for(Order order : orders){
                OrderMamgerListVo orderMamgerListVo = this.orderWrapOrderMamgerListVo(order);
                orderMamgerListVos.add(orderMamgerListVo);
            }
            resultMap.put(BaseCode.DATA,orderMamgerListVos);
            resultMap.put(BaseCode.CODE,BaseCode.SUCCESS_ERROR_CODE);
            resultMap.put(BaseCode.MSG,BaseCode.SUCCESS_ERROR_MSG);
        }else{
            //提示用户不存在
            resultMap.put(BaseCode.CODE,BaseCode.HPP_USER_NOT_EXSIT_CODE);
            resultMap.put(BaseCode.MSG,BaseCode.HPP_USER_NOT_EXSIT_MSG);
        }
        return resultMap;
    }

    public OrderMamgerListVo orderWrapOrderMamgerListVo(Order order){
        OrderMamgerListVo orderMamgerListVo = new OrderMamgerListVo();
        orderMamgerListVo.setCount(order.getCount());
        orderMamgerListVo.setJoinTime(DateHelper.formatDate(order.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
        orderMamgerListVo.setOrderNo(order.getOrderNo());
        orderMamgerListVo.setRecivePhone(order.getRecivePhone());
        orderMamgerListVo.setReciveName(order.getReciveName());
        HppUser collageUser = this.hppUserService.get(order.getSellerUserId());
        orderMamgerListVo.setCollageNickName(collageUser.getNickName());
        orderMamgerListVo.setCollagePhone(collageUser.getPhone());
        orderMamgerListVo.setReciveAddress(order.getAddress());
        orderMamgerListVo.setProvince(order.getProvince());
        orderMamgerListVo.setCity(order.getCity());
        orderMamgerListVo.setRegion(order.getRegion());
        //TODO 支付时间 支付单号
        return orderMamgerListVo;
    }

    /**
     * 我参加的团
     * @param example
     * @param userId
     * @return
     */
    public Map<String,Object> myJoinCollage(OrderExample example,String userId){
        Map<String,Object> resultMap = new HashMap<>();
        HppUser hppUser = this.hppUserService.get(userId);
        if(hppUser!=null){
            List<Order> orders = findMyJoinCollageByUserIdAndPage(example,userId);
            List<MyJoinCollageVo> myJoinCollageVos = new ArrayList<>();
            for(Order order : orders){
                Collage collage = this.collageService.get(order.getCollageId());
                MyJoinCollageVo myJoinCollageVo = new MyJoinCollageVo();
                //参团时间
                myJoinCollageVo.setJoinDate(DateHelper.formatDate(order.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
                //团长名称
                HppUser collageUser = this.hppUserService.get(collage.getUserId());
                myJoinCollageVo.setNickName(collageUser.getNickName());
                //团title
                myJoinCollageVo.setTitle(collage.getTitle());
                //拼团是否结束
                CollageEndState collageEndState = this.collageService.IsCollageEnd(collage);
                myJoinCollageVo.setState(collageEndState.getState());
                //是否成团
                CollageSuccess collageSuccess = this.collageService.isSuccessCollage(collage);
                myJoinCollageVo.setCollageSuccess(collageSuccess.getState());
                List<CollageImageVideo> collageImageVideos =this.collageImageVideoService.findCollageImageVideoByCollageIdAndType(collage.getId(),ImageVideoType.Image);
                if(!collageImageVideos.isEmpty())
                    myJoinCollageVo.setImage(collageImageVideos.get(0).getUrl());
                myJoinCollageVos.add(myJoinCollageVo);
            }
            resultMap.put(BaseCode.DATA,myJoinCollageVos);
            resultMap.put(BaseCode.CODE,BaseCode.SUCCESS_ERROR_CODE);
            resultMap.put(BaseCode.MSG,BaseCode.SUCCESS_ERROR_MSG);
        }else{
            //提示用户不存在
            resultMap.put(BaseCode.CODE,BaseCode.HPP_USER_NOT_EXSIT_CODE);
            resultMap.put(BaseCode.MSG,BaseCode.HPP_USER_NOT_EXSIT_MSG);
        }
        return resultMap;

    }

    /**
     * 查看我参加过的团 (除去未支付的订单)
     * @param example
     * @param userId
     * @return
     */
    public List<Order> findMyJoinCollageByUserIdAndPage(OrderExample example , String userId){
        Criteria criteria = example.createCriteria();
        criteria.andIsEffectiveEqualTo(DBConst.TRUE);
        criteria.andBuyUserIdEqualTo(userId);
        criteria.andStateNotEqualTo(OrderState.Paying.getState());
        return this.list(example);
    }

    /**
     * 修改订单状态
     * @param order
     * @param orderState
     * @return
     */
    public String editOrderState(Order order ,OrderState orderState){
        order.setState(orderState.getState());
        return this.edit(order);
    }

    /**
     *  确认收货
     * @param orderNo 订单号
     * @param userId 团长Id
     * @return
     */
    public Map<String,Object> confirmRecive(String orderNo,String userId){
        Map<String,Object> resultMap = new HashMap<>();
        Order order = this.getOrderByOrderNo(orderNo);
        if(order!=null){
             if(userId.equals(order.getBuyUserId())){
                OrderState orderState = OrderState.getOrderState(order.getState());
                 if(OrderState.Confirm.getState().equals(orderState.getState())){
                     //修改订单状态
                     String result = this.editOrderState(order,OrderState.Judging);
                     if(SUCCESS.equals(result)){
                         //支付方法
                         PayMethod payMethod = PayMethod.getPayMethod(order.getPayMethod());
                         switch (payMethod){
                             //直接到账
                             case DirectToAccount:
                                break;
                             case GuaranteePay:
                                 //担保支付:到账的钱打给团长余额 修改订单状态为已打款
                                 this.hppUserService.operateUserMoney(order.getSellerUserId(),order.getActualPay(),OperateType.add,FlowType.InCome,FlowMethod.OrderTrade,order.getOrderNo(),FlowSource.Order,order.getBuyUserId());
                                 break;
                         }
                         //修改订单状态 以及确认收货时间
                         order.setConfirmReciveTime(new Date());
                         this.editOrderState(order,OrderState.Judging);
                         resultMap.put(BaseCode.CODE,BaseCode.SUCCESS_ERROR_CODE);
                         resultMap.put(BaseCode.MSG,BaseCode.SUCCESS_ERROR_MSG);
                     }
                }else{
                    //收货状态不是待收货状态无法确认收货
                     resultMap.put(BaseCode.CODE,BaseCode.HPP_ORDER_STATE_NOT_CONFIRM_CODE);
                     resultMap.put(BaseCode.MSG,BaseCode.HPP_ORDER_STATE_NOT_CONFIRM_MSG);
                }
             }else{
                 //提示用户不一致
                 resultMap.put(BaseCode.CODE,BaseCode.HPP_SELF_USER_NOT_ACCORDANCE_CODE);
                 resultMap.put(BaseCode.MSG,BaseCode.HPP_SELF_USER_NOT_ACCORDANCE_MSG);
             }
        }else{
            //提示订单不存在
            resultMap.put(BaseCode.CODE,BaseCode.HPP_ORDER_NOT_EXIST_CODE);
            resultMap.put(BaseCode.MSG,BaseCode.HPP_ORDER_NOT_EXIST_MSG);
        }
        return resultMap;
    }

    /**
     * 发货
     * @param orderNo
     * @param userId
     * @param sendMethod
     * @param expressCode
     * @param expressNo
     * @return
     */
    public Map<String,Object> deliverGood(String orderNo,String userId,SendMethod sendMethod,String expressCode,String expressNo){
        Map<String,Object> resultMap = new HashMap<>();
        Order order = this.getOrderByOrderNo(orderNo);
        //查看订单是否存在
        if(order!=null){
            OrderState orderState = OrderState.getOrderState(order.getState());
            //查看订单是否处于待发货状态
            if(OrderState.Sending.getState().equals(orderState.getState())){
                Collage collage = this.collageService.get(order.getCollageId());
                if(collage!=null){
                    //效验是否成团 不成团不允许发货
                    CollageSuccess collageSuccess = this.collageService.isSuccessCollage(collage);
                    if(CollageSuccess.Success.getState().equals(collageSuccess.getState())){
                        //效验拼团发货方式参数
                        switch (sendMethod){
                            case Express:
                                // 根据快递code查询物流公司
                                ProjectExpress projectExpress = this.projectExpressService.getProjectExpressByCode(expressCode);
                                if(projectExpress !=null){
                                    this.editOrderExpress(projectExpress,order,sendMethod,expressNo);
                                    //发货成功
                                    resultMap.put(BaseCode.CODE,BaseCode.SUCCESS_ERROR_CODE);
                                    resultMap.put(BaseCode.MSG,BaseCode.SUCCESS_ERROR_MSG);
                                }else{
                                    //快递公司不存在
                                    resultMap.put(BaseCode.CODE,BaseCode.HPP_PROJECT_EXPRESS_NOT_EXIST_CODE);
                                    resultMap.put(BaseCode.MSG,BaseCode.HPP_PROJECT_EXPRESS_NOT_EXIST_MSG);
                                }
                                    break;
                                case MySelf:
                                    this.editOrderMyself(order,sendMethod);
                                    //发货成功
                                    resultMap.put(BaseCode.CODE,BaseCode.SUCCESS_ERROR_CODE);
                                    resultMap.put(BaseCode.MSG,BaseCode.SUCCESS_ERROR_MSG);
                                    break;
                            }
                    }else{
                        //拼团未成团不允许发货
                        resultMap.put(BaseCode.CODE,BaseCode.HPP_COLLAGE_NOT_SUCCESS_IS_NOT_SEND_CODE);
                        resultMap.put(BaseCode.MSG,BaseCode.HPP_COLLAGE_NOT_SUCCESS_IS_NOT_SEND_MSG);
                    }
                }else{
                    //提示拼团不存在
                    resultMap.put(BaseCode.CODE,BaseCode.HPP_COLLAGE_NOT_EXIST_CODE);
                    resultMap.put(BaseCode.MSG,BaseCode.HPP_COLLAGE_NOT_EXIST_MSG);
                }
            }else{
                //提示该订单不处于代发货状态
                resultMap.put(BaseCode.CODE,BaseCode.HPP_ORDER_STATE_NOT_SEND_CODE);
                resultMap.put(BaseCode.MSG,BaseCode.HPP_ORDER_STATE_NOT_SEND_MSG);
            }
        }else{
            //提示订单不存在
            resultMap.put(BaseCode.CODE,BaseCode.HPP_ORDER_NOT_EXIST_CODE);
            resultMap.put(BaseCode.MSG,BaseCode.HPP_ORDER_NOT_EXIST_MSG);
        }
        return resultMap;
    }

    /**
     * 编辑订单发货物流
     * @param express
     * @param order
     * @param sendMethod
     * @return
     */
    public String editOrderExpress(ProjectExpress express,Order order,SendMethod sendMethod,String expressNo){
        order.setExpressId(express.getId());
        order.setExpressName(express.getExpressCompany());
        order.setExpressNo(expressNo);
        order.setSendMethod(sendMethod.getState());
        order.setState(OrderState.Confirm.getState());
        return this.edit(order);
    }

    /**
     * 编辑订单发货自己配送
     * @param order
     * @param sendMethod
     * @return
     */
    public String editOrderMyself(Order order,SendMethod sendMethod){
        order.setSendMethod(sendMethod.getState());
        order.setState(OrderState.Confirm.getState());
        return this.edit(order);
    }

    /**
     * 查看一个拼团参团的订单(已付款订单)
     * @param collageId
     * @return
     */
    public List<Order> findJoinCollageOrderByCollageId(String collageId){
        OrderExample example = new OrderExample();
        Criteria criteria = example.createCriteria();
        criteria.andIsEffectiveEqualTo(DBConst.TRUE);
        criteria.andStateEqualTo(OrderState.Sending.getState());
        criteria.andCollageIdEqualTo(collageId);
        List<Order> orders = this.list(example);
        return orders;
    }

    /**
     * 申请退款效验以及申请退款业务
     * @param orderNo
     * @param userId
     * @return
     */
    public Map<String,Object>  applyOrderAfterSale(String orderNo,String userId){
        Map<String,Object> resultMap = new HashMap<>();
        Order order = this.getOrderByOrderNo(orderNo);
        if(order!=null){
            if(userId.equals(order.getBuyUserId())){
                Collage collage = this.collageService.get(order.getCollageId());
                if(collage!=null){
                    //效验拼团是否成团
                    CollageSuccess collageSuccess = this.collageService.isSuccessCollage(collage);
                    if(CollageSuccess.Success.getState().equals(collageSuccess.getState())){
                        //效验拼团是否是直接到账，若直接到账 提示线下自己联系。
                        PayMethod payMethod = PayMethod.getPayMethod(collage.getPayMethod());
                        if(!PayMethod.DirectToAccount.getMethod().equals(payMethod.getMethod())){
                            //效验订单状态是否可以申请退款
                            OrderState orderState = OrderState.getOrderState(order.getState());
                            switch(orderState){
                                case Paying:
                                case Judging:
                                case ApplyRefund:
                                    //提示订单状态不合符申请退款状态
                                    resultMap.put(BaseCode.CODE,BaseCode.HPP_ORDER_STATE_NOT_APPLY_REFUND_CODE);
                                    resultMap.put(BaseCode.MSG,BaseCode.HPP_ORDER_STATE_NOT_APPLY_REFUND_MSG);
                                    break;
                                case Sending:
                                case Confirm:
                                    //申请退款业务逻辑
                                    this.applyAfterSale(order);
                                    resultMap.put(BaseCode.CODE,BaseCode.SUCCESS_ERROR_CODE);
                                    resultMap.put(BaseCode.MSG,BaseCode.SUCCESS_ERROR_MSG);
                                    break;
                            }
                        }else{
                            //效验拼团是否是直接到账，若直接到账 提示线下自己联系。
                            resultMap.put(BaseCode.CODE,BaseCode.HPP_COLLAGE_IS_DIRECT_SELF_CONTACT_CODE);
                            resultMap.put(BaseCode.MSG,BaseCode.HPP_COLLAGE_IS_DIRECT_SELF_CONTACT_MSG);
                        }
                    }else{
                        //提示拼团未成团不能申请退款
                        resultMap.put(BaseCode.CODE,BaseCode.HPP_COLLAGE_NOT_SUCCESS_NOT_APPLY_REFUND_CODE);
                        resultMap.put(BaseCode.MSG,BaseCode.HPP_COLLAGE_NOT_SUCCESS_NOT_APPLY_REFUND_MSG);
                    }
                }else{
                    //提示拼团不存在
                    resultMap.put(BaseCode.CODE,BaseCode.HPP_COLLAGE_NOT_EXIST_CODE);
                    resultMap.put(BaseCode.MSG,BaseCode.HPP_COLLAGE_NOT_EXIST_MSG);
                }

            }else{
                //提示用户不一致
                resultMap.put(BaseCode.CODE,BaseCode.HPP_SELF_USER_NOT_ACCORDANCE_CODE);
                resultMap.put(BaseCode.MSG,BaseCode.HPP_SELF_USER_NOT_ACCORDANCE_MSG);
            }
        }else{
            //提示订单不存在
            resultMap.put(BaseCode.CODE,BaseCode.HPP_ORDER_NOT_EXIST_CODE);
            resultMap.put(BaseCode.MSG,BaseCode.HPP_ORDER_NOT_EXIST_MSG);
        }
        return resultMap;

    }

    /**
     * 申请退款处理业务
     * @param order
     * @return
     */
    public String applyAfterSale(Order order){
        //修改订单状态为退款申请状态
        String result = this.editOrderState(order,OrderState.ApplyRefund);
        if(SUCCESS.equals(result)){
            //添加一条售后记录
            result = this.orderAfterSaleService.addOrderAfterSale(order.getBuyUserId(),order,order.getActualPay(),order.getCollageId());
        }
        return result;
    }

    /**
     * 同意售后
     * @param orderNo
     * @param userId
     * @return
     */
    public Map<String,Object> agreeAfterSale(String orderNo,String userId){
        Map<String,Object> resultMap = new HashMap<>();
        Order order = this.getOrderByOrderNo(orderNo);
        if(order!=null){
            if(userId.equals(order.getSellerUserId())){
                //效验订单状态
                OrderState orderState = OrderState.getOrderState(order.getState());
                if(OrderState.ApplyRefund.getState().equals(orderState.getState())){
                    //效验订单是否是直接到账
                    PayMethod payMethod = PayMethod.getPayMethod(order.getPayMethod());
                    if(!PayMethod.DirectToAccount.getMethod().equals(payMethod.getMethod())){
                        TradeCollageType tradeCollageType = TradeCollageType.getTradeCollageType(order.getIsTradeCollage());
                        if(TradeCollageType.No.getType().equals(tradeCollageType.getType())){
                            OrderAfterSale orderAfterSale = this.orderAfterSaleService.getOrderAfterSaleByOrderNo(order.getOrderNo());
                            if(orderAfterSale!=null){
                                //效验售后状态
                                DealState dealState = DealState.getDealState(orderAfterSale.getDealState());
                                if(DealState.Apply.getState().equals(dealState.getState())){
                                    //处理退款业务
                                    this.dealOrderAfterSale(order,orderAfterSale);
                                    resultMap.put(BaseCode.CODE,BaseCode.SUCCESS_ERROR_CODE);
                                    resultMap.put(BaseCode.MSG,BaseCode.SUCCESS_ERROR_MSG);
                                }else{
                                    //提示售后状态不对
                                    resultMap.put(BaseCode.CODE,BaseCode.HPP_ORDER_ALTERSALE_STATE_ERROR_CODE);
                                    resultMap.put(BaseCode.MSG,BaseCode.HPP_ORDER_ALTERSALE_STATE_ERROR_MSG);
                                }
                            }else{
                                //提示售后不存在
                                resultMap.put(BaseCode.CODE,BaseCode.HPP_ORDER_ALTERSALE_NOT_EXIST_CODE);
                                resultMap.put(BaseCode.MSG,BaseCode.HPP_ORDER_ALTERSALE_NOT_EXIST_MSG);
                            }
                        }else{
                            //已经打款 请线下联系
                            resultMap.put(BaseCode.CODE,BaseCode.HPP_ORDER_ALREADY_PAY_SELF_CONTACT_CODE);
                            resultMap.put(BaseCode.MSG,BaseCode.HPP_ORDER_ALREADY_PAY_SELF_CONTACT_MSG);
                        }
                    }else{
                        //提示拼团是直接到账 请线下联系
                        resultMap.put(BaseCode.CODE,BaseCode.HPP_COLLAGE_IS_DIRECT_SELF_CONTACT_CODE);
                        resultMap.put(BaseCode.MSG,BaseCode.HPP_COLLAGE_IS_DIRECT_SELF_CONTACT_MSG);
                    }
                }else{
                    //提示订单状态不对
                    resultMap.put(BaseCode.CODE,BaseCode.HPP_ORDER_STATE_NOT_APPLY_REFUND_CODE);
                    resultMap.put(BaseCode.MSG,BaseCode.HPP_ORDER_STATE_NOT_APPLY_REFUND_MSG);
                }
            }else{
                //提示用户不一致
                resultMap.put(BaseCode.CODE,BaseCode.HPP_SELF_USER_NOT_ACCORDANCE_CODE);
                resultMap.put(BaseCode.MSG,BaseCode.HPP_SELF_USER_NOT_ACCORDANCE_MSG);
            }
        }else{
            //提示订单不存在
            resultMap.put(BaseCode.CODE,BaseCode.HPP_ORDER_NOT_EXIST_CODE);
            resultMap.put(BaseCode.MSG,BaseCode.HPP_ORDER_NOT_EXIST_MSG);
        }
        return resultMap;
    }

    /**
     * 退款业务处理
     * @param order
     * @param orderAfterSale
     * @return
     */

    public String  dealOrderAfterSale(Order order, OrderAfterSale orderAfterSale){
        DealState dealState = DealState.RefundIng;
        String reason = null;
        String outRefundNo = IdGen.uuid();
        try {
            WXRefundResult wxRefundResult =  WeixinUtil.wxRefundResult(HPPConfig.APPID,HPPConfig.MCHID,HPPConfig.APPKEY,HPPConfig.CALICENSE,outRefundNo,order.getOrderNo(),Double.toString(order.getActualPay()),Double.toString(order.getActualPay()));
            if("SUCCESS".equals(wxRefundResult.getError_code())) {
                dealState = DealState.RefundSuccess;
            }else {
                dealState = DealState.RefundFail;
                reason = wxRefundResult.getError_reson();
            }
        } catch (Exception e) {
            e.printStackTrace();
            dealState = DealState.RefundFail;
            reason = "服务器异常";
        }
        String result = this.orderAfterSaleService.editOrderAfterSaleState(orderAfterSale,dealState,outRefundNo,reason);
        return result;
    }

    /**
     * 担保或者直接到账 打钱给团长用户上
     * @param order
     * @param collageUserId
     */
    public void  paymentToCollageHead(Order order , String  collageUserId){
        TradeCollageType tradeCollageType = TradeCollageType.getTradeCollageType(order.getIsTradeCollage());
        //效验订单是否打过款给团长
        if(tradeCollageType.getType().equals(TradeCollageType.No.getType())){
            //打款给团长
            String result = this.hppUserService.operateUserMoney(order.getSellerUserId(),order.getActualPay(),OperateType.add,FlowType.InCome,FlowMethod.OrderTrade,order.getOrderNo(),FlowSource.Order,order.getBuyUserId());
            if(SUCCESS.equals(result)){
                //修改订单已打款给团长
                order.setIsTradeCollage(TradeCollageType.YES.getType());
                this.edit(order);
            }
        }
    }

    /**
     * 订单物流状态
     * @param orderNo
     * @return
     */
   public Map<String,Object> expressInfo(String orderNo){
        Map<String,Object> resultMap = new HashMap<>();
        Order order = this.getOrderByOrderNo(orderNo);
        if(order!=null){
            OrderState orderState = OrderState.getOrderState(order.getState());
            if(OrderState.Confirm.getState().equals(orderState.getState()) || OrderState.Judging.getState().equals(orderState.getState())){
                SendMethod sendMethod = SendMethod.getSendMethod(order.getSendMethod());
                switch (sendMethod){
                    case MySelf:
                        //提示订单是团长自己配送
                        resultMap.put(BaseCode.CODE,BaseCode.HPP_ORDER_COLLAGE_SELF_SEND_CODE);
                        resultMap.put(BaseCode.MSG,BaseCode.HPP_ORDER_COLLAGE_SELF_SEND_MSG);
                        break;
                    case Express:
                        String expressId = order.getExpressId();
                        ProjectExpress projectExpress = this.projectExpressService.get(expressId);
                        String expressNo = order.getExpressNo();
                        Object obj = ExpressUtil.getWuliuMsgByCodeAndNum("yd","3937124702477");
                        Map<String,Object> data = new HashMap<>();
                        data.put("expressInfo",obj);
                        data.put("expressName",projectExpress.getExpressCompany());
                        data.put("expressNo",expressNo);
                        List<CollageImageVideo> collageImageVideos = this.collageImageVideoService.findCollageImageVideoByCollageIdAndType(order.getCollageId(),ImageVideoType.Image);
                        if(!collageImageVideos.isEmpty())
                            data.put("mainImage",collageImageVideos.get(0).getUrl());
                        resultMap.put(BaseCode.DATA,data);
                        resultMap.put(BaseCode.CODE,BaseCode.SUCCESS_ERROR_CODE);
                        resultMap.put(BaseCode.MSG,BaseCode.SUCCESS_ERROR_MSG);
                        break;
                }
            }else{
                //订单未发货
                resultMap.put(BaseCode.CODE,BaseCode.HPP_ORDER_NOT_SEND_CODE);
                resultMap.put(BaseCode.MSG,BaseCode.HPP_ORDER_NOT_SEND_MSG);
            }
        }else{
            //订单不存在
            resultMap.put(BaseCode.CODE,BaseCode.HPP_ORDER_NOT_EXIST_CODE);
            resultMap.put(BaseCode.MSG,BaseCode.HPP_ORDER_NOT_EXIST_MSG);

        }
        return resultMap;
   }

}